<?php
//商家列表
namespace app\ausagent\controller;
use app\ausagent\controller\Common;
use think\Request;
use think\Db;
use think\File;
use think\Config;
use think\Session;
use think\Cookie;
use Godok\Org\FileManager;
use Qcloud\cos\Api;
class Seller extends Common
{
	public function sellerlist(){
		//定义每页显示记录数
		$pages = 20;
		//定义where条件
		$where = 'a.is_delete = 1 AND a.status = 1 AND a.oid = '.Session::get('oid');
		$pageParam    = ['query' =>[]];
		//判断是否有按商户名称查询
		if(!empty(input('name'))){
			$where .= ' AND a.name LIKE '."'%".input('name')."%' ";
			$pageParam['query']['name'] = input('name');
			$this->assign('name',input('name'));
		}
		
		//判断是否按所在区域查询
		if(!empty(input('area'))){
			$where .= ' AND a.area LIKE '."'%".input('area')."%'";
			$pageParam['query']['area'] = input('area');
			$this->assign('area',input('area'));
		}
		/*$u = Config::get('auth.table_user');//定义用户表
		$list= Db::name( 'seller')
				->alias('a')
				->join("$u b",'a.oid = b.oid and a.salesman = b.id')
				->field('a.id,a.salesman,a.phone,a.area,a.addr,a.longitude,a.latitude,a.picture,a.shopstart,a.shopend,a.averageprice,a.brokerage,a.name,b.nickname')
                ->where($where)
                ->order('a.create_time DESC')
				->paginate($pages, false, $pageParam);*/
		//$u = Config::get('operator_users');//定义用户表
		$list = Db::name('seller')
				->alias('a')
				->join('operator_users b','a.create_user =b.id and a.oid=b.oid')
				->where($where)
				->where(['a.is_delete'=>1,'a.status'=>1,'a.oid'=>session('oid')])
				->field('a.id,a.salesman,a.phone,a.area,a.addr,a.longitude,a.latitude,a.picture,a.shopstart,a.shopend,a.averageprice,a.brokerage,a.name,b.username,b.nickname')
				->order('create_time desc')
				->paginate($pages, false, $pageParam);
		//echo Db::name('seller')->getlastsql();
		
		//var_dump($list); die;
		$this->assign('list',$list);
		
		return $this->fetch();
	}

	public function add(){

		if ( Request::instance()->isPost()) {
			//var_dump(input('post.')); die;
			if($_FILES['picture']['name']){
				$file = Request::instance()->file('picture');
				$info=$file->move(ROOT_PATH . 'public' . DS . 'uploads');
				$file = $info->getSaveName();
				if($file){
                    $cosApi = new Api(config('Qcloud'));
                    $bucket = config('Qcloud.bucket');
                    $src = ROOT_PATH . 'public/uploads/'.$file;
                    $dst = 'operator/seller/'. $file;
                    $ret = $cosApi->upload($bucket, $src, $dst);
					if($ret['code']==0){
	                    $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
	                    $len = strlen($bucket);  //计算bucketname长度
	                    $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
	                    $start +=$len;  
	                    $newpath = substr($path,$start);  //截取路径
	                    unlink($src);  //删除服务器上面的资源文件
	                    $res['code'] = '1';
	                    $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
	                    $res['url'] = $ret['data']['access_url'];   //资源文件URL
	                    $data['picture'] = $res['picture'];
	                }   
                }
		        //$data['picture'] = $file;
			}
			$data['name']= input('name');
			$data['phone']= input('phone');
			$data['area']= input('area');
			$data['addr']= input('addr');
			$data['averageprice'] = input('averageprice');
			$data['longitude']= input('longitude');
			$data['latitude']= input('latitude');
			$data['shopstart']= str_replace(':','',input('shopstart'));
			$data['shopend'] = str_replace(':','',input('shopend'));
			$data['brokerage'] = input('brokerage');
			$data['create_time'] = time();
			$data['is_delete'] = 1;
			$data['salesman'] = session('id');
			$data['create_user'] = session('id');
			$data['oid'] = session('oid');
			$name = input('name');
			$check = Db::name('seller')->where(['name'=>$name,'is_delete'=>1])->find();
			if($check){
				return ['code'=>-1050, 'msg'=>'商户名称已存在!'];
			}
			$cid = input('cabinet_id');
			$result = Db::name('charecabinet')->where('id',$cid)->find();
			if(Db::name( 'seller')->insert($data)){
				$sid = Db::name('seller')->getLastInsID();
				$cdate['sid'] = $sid;
				Db::name('charecabinet')->where('id',$cid)->update($cdate);
		    	//$this->redirect('sellerlist');
		    	$oid = session('oid');$m = 'ausagent'; $c = 'Seller'; $action="add"; $uid=session('id'); $querystring = '添加商户信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
		    	return ['code'=>0, 'msg'=>'添加成功！'];
		    	//return;
    		}else{
    			//$this->error('添加失败！');
    			return ['code'=>-1050, 'msg'=>'添加失败！'];
    		}
    		
		}

		$ret = Db::name('charecabinet')->where(['is_delete'=>1,'oid'=>session('oid'),'sid'=>0])->select();
		$this->assign('list',$ret);
		return $this->fetch();
	}

	public function edit($id='',$data= ''){
		
		if ( Request::instance()->isPost()) {
			//var_dump(input('post.')); die;
			if($_FILES['picture']['name']){
				$file = Request::instance()->file('picture');
				$info=$file->move(ROOT_PATH . 'public' . DS . 'uploads');
				$file = $info->getSaveName();
				if($file){
                    $cosApi = new Api(config('Qcloud'));
                    $bucket = config('Qcloud.bucket');
                    $src = ROOT_PATH . 'public/uploads/'.$file;
                    $dst = 'operator/seller/'. $file;
                    $ret = $cosApi->upload($bucket, $src, $dst);
					if($ret['code']==0){
	                    $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
	                    $len = strlen($bucket);  //计算bucketname长度
	                    $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
	                    $start +=$len;  
	                    $newpath = substr($path,$start);  //截取路径
	                    unlink($src);  //删除服务器上面的资源文件
	                    $res['code'] = '1';
	                    $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
	                    $res['url'] = $ret['data']['access_url'];   //资源文件URL
	                    $data['picture'] = $res['picture'];
	                }   
                }
		        //$data['picture'] = $file;
			}
			$data['id'] = input('id');
			$data['name']= input('name');
			$data['phone']= input('phone');
			$data['averageprice'] = input('averageprice');
			$data['area']= input('area');
			$data['addr']= input('addr');
			$data['longitude']= input('longitude');
			$data['latitude']= input('latitude');
			$data['shopstart']= str_replace(':','',input('shopstart'));
			$data['shopend'] = str_replace(':','',input('shopend'));
			$data['brokerage'] = input('brokerage');
			$name = input('name');
			$sid = (int)input('id');
			$check = Db::name('seller')->where('id','<>',$sid)->where('name',$name)->find();
			if($check){
				return ['code'=>-1050, 'msg'=>'商户名称已存在!'];
			}
			//var_dump($data); die;
			if(Db::name( 'seller')->update($data)){
		    	//$this->redirect('sellerlist');
		    	$oid = session('oid');$m = 'ausagent'; $c = 'Seller'; $action="edit"; $uid=session('id'); $querystring = '编辑商户信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
		    	return ['code'=>0, 'msg'=>'修改成功！'];
    		}else{
    			//$this->error('添加失败！');
    			return ['code'=>-1050, 'msg'=>'修改失败！'];
    		}

		}else{
			$id =  Request::instance()->get('id','','number_int');
			if(!empty($id)){
				$where = 'id = '.$id;
				$jquery = Db::name('seller')->where($where)->find();
				$this->assign('v',$jquery);
				return $this->fetch();
			}else{
				die('非法访问!');
			}
			
		}
		
	}

	public function delete($id=''){
		$id =  Request::instance()->get('id','','number_int');
		$data['id'] = $id;
		$data['is_delete'] = 0; 
		if(Db::name( 'seller')->update($data)){
    			//$this->redirect('index');
    		$ret = Db::name('charecabinet')->where('sid',$id)->find();
    		Db::name('charecabinet')->where('id',$ret['id'])->setField('sid', 0);
    		$oid = session('oid');$m = 'ausagent'; $c = 'Seller'; $action="delete"; $uid=session('id'); $querystring = '删除商户 '.$id.' 信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
    		return ['code'=>0, 'msg'=>'删除成功！'];
		}else{
			return ['code'=>-1050, 'msg'=>'删除失败！'];
		}

	}


}